﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ucCategory : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }

    private void BindGrid()
    {
        CategoryBL obj = new CategoryBL();
        GridView1.DataSource = obj.GetMainCategories();
        GridView1.DataBind();
    }

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        BindGrid();
    }

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        long categoryId = Convert.ToInt64(GridView1.DataKeys[e.RowIndex].Values[0]);
        TextBox TextBox1 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1");
        var login = (LoginBL)Session["User"];
        CategoryBL obj = new CategoryBL(categoryId, TextBox1.Text, "0", login.UserId);
        if (obj.Update())
        {
            BindGrid();
        }
        else
        {
            Response.Write("<script>alert('Server Problem! Try Again.')</script>");
        }
        GridView1.EditIndex = -1;
        BindGrid();
    }

    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        BindGrid();
    }

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        long categoryId = Convert.ToInt64(GridView1.DataKeys[e.RowIndex].Values[0]);
        CategoryBL obj = new CategoryBL(categoryId);
        if (obj.Delete())
        {
            BindGrid();
        }
        else
        {
            Response.Write("<script>alert('Server Problem! Try Again.')</script>");
        }
        BindGrid();
    }

    protected void btnAddCategory_Click(object sender, EventArgs e)
    {
        var login = (LoginBL)Session["User"];
        CategoryBL obj = new CategoryBL(txtCategoryName.Text, "0", login.UserId);
        if (obj.Insert())
        {
            BindGrid();
        }
        else
        {
            Response.Write("<script>alert('Server Problem! Try Again.')</script>");
        }
    }
}